/*
 * @Author: TC (tengchao@taqu.cn)
 * @Date: 2025-10-17 16:29:27
 * @Last Modified by: TC (tengchao@taqu.cn)
 * @Last Modified time: 2025-10-17 17:09:30
 */

import { app } from "db://assets/FrameWork/App";
import { nsMoleEnum } from "../Const/MoleEunm";
import { Node, Tween, tween, UIOpacity, UITransform, v3 } from "cc";
import { gameMole } from "../GameMole";
import { nsMath } from "db://assets/FrameWork/Util/MathUtil";

/**
 * 帽子管理
 */
export class MoleCapManager {
    private _capList: Node[] = [];

    /**
     * 获取帽子
     * @returns
     */
    public getCap(): Node {
        const nodeCap = app.poolMgr.getItem(nsMoleEnum.EPoolName.CAP);
        nodeCap.getComponent(UIOpacity).opacity = 255;
        this._capList.push(nodeCap);
        const rad = nsMath.getRandomNum(0, 4);
        nodeCap.children.forEach((c, index) => {
            c.active = index == rad;
        });
        return nodeCap;
    }

    /**
     * 移除帽子
     * @param nodeCap
     */
    public removeCap(nodeCap: Node): void {
        if (nodeCap) {
            Tween.stopAllByTarget(nodeCap);
            Tween.stopAllByTarget(nodeCap.getComponent(UIOpacity));
            const index = this._capList.indexOf(nodeCap);
            if (index != -1) {
                this._capList.splice(index, 1);
            }
            app.poolMgr.putItem(nsMoleEnum.EPoolName.CAP, nodeCap);
        }
    }

    /**
     * 播放帽子动画
     * @param nodeCap
     */
    public playCapAni(nodeCap: Node): void {
        Tween.stopAllByTarget(nodeCap);
        const nodeParent = gameMole.battleMgr.layerHole;
        const pos = nodeParent.getComponent(UITransform).convertToNodeSpaceAR(nodeCap.worldPosition);
        nodeCap.parent = nodeParent;
        nodeCap.setPosition(pos);

        tween(nodeCap)
            .parallel(
                tween(nodeCap)
                    .by(0.15, { position: v3(15, 50, 0) })
                    .by(0.25, { position: v3(25, -110, 0) })
                    .call(() => {
                        this.removeCap(nodeCap);
                    })
                    .union()
            )
            .start();
        tween(nodeCap.getComponent(UIOpacity)).delay(0.2).to(0.4, { opacity: 0 }).start();
    }

    /**
     * 释放
     */
    public release(): void {
        this._capList.forEach((nodeCap) => {
            Tween.stopAllByTarget(nodeCap);
            Tween.stopAllByTarget(nodeCap.getComponent(UIOpacity));
            app.poolMgr.putItem(nsMoleEnum.EPoolName.CAP, nodeCap);
        });
        this._capList.length = 0;
    }
}
